package cn.com.xy.sms.sdk.ui.popu.widget;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import cn.com.xy.sms.sdk.ui.R;
import cn.com.xy.sms.sdk.ui.popu.util.ChannelContentUtil;
import cn.com.xy.sms.sdk.util.StringUtils;

public class AirTrainSelectDialog {
	private JSONArray mTrainArray;
	private Context mContext;
	private int mCurrentTrainIndex;
	private List<View> mAllSelects;
	private OnBottomClick mOnBottomClick = null;
	private AlertDialog mAlertDialog ;
	public static final int CONFIRM = 0;
	public static final int CANNEL = 1;
	public DialogParams mParams;
    private int mState;

	public AirTrainSelectDialog(JSONArray train_array, Context mContext, int mCurrentTrainIndex) {
		super();
		this.mTrainArray = train_array;
		this.mContext = mContext;
		this.mCurrentTrainIndex = mCurrentTrainIndex;
		mAllSelects = new ArrayList<View>();

		mParams = new DialogParams();
		mParams.mDefaultTitleName = "";
	}
    

    public AirTrainSelectDialog(JSONArray train_array, Context context, int currentTrainIndex, int state) {
        super();
        this.mTrainArray = train_array;
        this.mContext = context;
        this.mCurrentTrainIndex = currentTrainIndex;
        this.mState = state;
        mAllSelects = new ArrayList<View>();

        mParams = new DialogParams();
        mParams.mDefaultTitleName = "";
    }
	
	
	@SuppressLint("ResourceAsColor")
    public void showAlertDialog(OnBottomClick click) {
        this.mOnBottomClick = click;
        if (mTrainArray != null && mTrainArray.length() > 0) {
            AlertDialog.Builder builder =new AlertDialog.Builder(mContext); 
            builder.setTitle(mParams.mDefaultTitleName);
            builder.setNegativeButton(mContext.getString(R.string.duoqu_ui_part_cancel), new DialogInterface.OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mAlertDialog.dismiss();
                    if (mOnBottomClick != null) {
                        mOnBottomClick.Onclick(CANNEL, mCurrentTrainIndex);
                    }
                }
            });
            
            View customView = LayoutInflater.from(mContext).inflate(R.layout.duoqu_select_list_dialog, null);
            builder.setCancelable(true);
            LinearLayout rootLayout = (LinearLayout) customView.findViewById(R.id.item_roots);
            for (int position = 0; position < mTrainArray.length(); position++) {
                JSONObject itemJson = mTrainArray.optJSONObject(position);
                View itemChildView = View.inflate(mContext, R.layout.duoqu_list_items_content_part, null);
                
                TextView itemCity = (TextView) itemChildView.findViewById(R.id.item_city);
                LinearLayout itemLayout = (LinearLayout) itemChildView.findViewById(R.id.item_layout);
                String departCity = itemJson.optString("view_depart_city");
                String departTerminal = itemJson.optString("view_depart_terminal");
                String departAirport = itemJson.optString("view_depart_airport");
                String arriveCity = itemJson.optString("view_arrive_city");
                String arriveTerminal = itemJson.optString("view_arrive_terminal");
                String arriveAirport = itemJson.optString("view_arrive_airport");
                
                DisplayMetrics metrics = ChannelContentUtil.getDisplayMetrics();
                ViewGroup.LayoutParams layoutParams = itemLayout.getLayoutParams();

                if (StringUtils.isNull(departCity) && StringUtils.isNull(arriveCity)) {
                    layoutParams.height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 48, metrics);
                    itemCity.setVisibility(View.GONE);
                } else {
                    layoutParams.height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 60, metrics);
                    arriveCity = getIntegrationData(arriveCity, arriveAirport, arriveTerminal);
                    departCity = getIntegrationData(departCity, departAirport, departTerminal);
                    
                    if (!StringUtils.isNull(arriveCity) && !StringUtils.isNull(departCity)) {
                        itemCity.setText(departCity + "—" + arriveCity);
                    } else if (!StringUtils.isNull(arriveCity)) {
                        itemCity.setText((mState == ChannelContentUtil.IS_FLIGHT ? ChannelContentUtil.FILGHT
                                : ChannelContentUtil.DIRECTION) + arriveCity);
                    } else if (!StringUtils.isNull(departCity)) {
                        itemCity.setText(departCity + ChannelContentUtil.DEPARTURE);
                    }
                    itemCity.setVisibility(View.VISIBLE);
                }
                itemLayout.setLayoutParams(layoutParams);

                TextView itemText = (TextView) itemChildView.findViewById(R.id.item_text);
                if (mState == ChannelContentUtil.IS_FLIGHT) {
                    itemText.setText(itemJson.optString(mParams.mSelectItemKey) + ChannelContentUtil.FIGHT);
                } else{
                    /* SMARTISAN-301 zhaoxiachao 20161206 start */
                    itemText.setText(itemJson.optString(mParams.mSelectItemKey));
                    /* SMARTISAN-301 zhaoxiachao 20161206 end */
                }

                RadioButton itemCheck = (RadioButton) itemChildView.findViewById(R.id.item_check);
                if (position == mCurrentTrainIndex) {
                    itemCheck.setChecked(true);
                } else {
                    itemCheck.setChecked(false);
                }
                itemChildView.setOnClickListener(new OnItemSelectDialog());
                mAllSelects.add(itemChildView);
                rootLayout.addView(itemChildView);
                
                if(position != mTrainArray.length() - 1){
                    View spliteView = new View(mContext);
                    spliteView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 2));
                    spliteView.setBackgroundResource(R.color.item_splite_color);
                    rootLayout.addView(spliteView);
                }
            }
            builder.setView(customView);
            mAlertDialog = builder.create();
            mAlertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            mAlertDialog.show();
            Window window = mAlertDialog.getWindow();
            window.setGravity(Gravity.CENTER);
            WindowManager.LayoutParams lp = window.getAttributes();
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            window.setAttributes(lp);
        }
    }

    // 获取集成数据
    private String getIntegrationData(String city, String airport, String terminal){
        if(!StringUtils.isNull(city) &&!StringUtils.isNull(airport) && !StringUtils.isNull(terminal)){
            city += " " + airport + terminal;
        } else if (!StringUtils.isNull(city) &&!StringUtils.isNull(airport)) {
            city += " " + airport;
        }else if (!StringUtils.isNull(city) &&!StringUtils.isNull(terminal)) {
            city += " " + terminal;
        }else if (!StringUtils.isNull(airport) && !StringUtils.isNull(terminal)){
            city = airport + terminal;
        }else if (!StringUtils.isNull(airport)){
            city = airport;
        }else if(!StringUtils.isNull(terminal)){
            city = terminal;
        }
        
        return city;
    }

	private class OnItemSelectDialog implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			for (int i = 0; i < mAllSelects.size(); i++) {
				View item = mAllSelects.get(i);
				if (item == v) {
//					RadioButton itemCheck = (RadioButton) item.findViewById(R.id.item_check);
//					itemCheck.setChecked(true);
					mCurrentTrainIndex = i;
					
					mAlertDialog.dismiss();
                    if (mOnBottomClick != null) {
                        mOnBottomClick.Onclick(CONFIRM, mCurrentTrainIndex);
                    }
                    break;
				}
//				else {
//				    RadioButton itemCheck = (RadioButton) item.findViewById(R.id.item_check);
//					itemCheck.setChecked(false);
//				}
			}
		}
	}

	public interface OnBottomClick {
		public void Onclick(int type, int select);
	}

	public class DialogParams {
		public String mDefaultTitleName;
		public String mSelectItemKey;
	}
}
